package com.app.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.app.model.User;
import com.app.util.AppSecurityUtil;

@Controller
public class LoginController {
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView getLoginPage(
			@RequestParam(value = "error", required = false) String error,
			ModelMap model, HttpServletRequest request) {
		if (!(AppSecurityUtil.isAnonymousUser())) {
			return new ModelAndView("redirect:success");
		}
		if (error != null) {
			model.addAttribute("error_msg",
					getErrorMessage(request, "SPRING_SECURITY_LAST_EXCEPTION"));
		}
		return new ModelAndView("login", "command", new User());
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public ModelAndView logout(HttpServletRequest request, ModelMap map) {
		return new ModelAndView("redirect:login");
	}

	@RequestMapping(value = "/success", method = RequestMethod.GET)
	public ModelAndView loginSuccess(ModelMap model, HttpServletRequest request) {
		if (AppSecurityUtil.isAnonymousUser()) {
			return new ModelAndView("redirect:login");
		}
		return new ModelAndView("success");
	}

	private String getErrorMessage(HttpServletRequest request, String key) {

		Exception exception = (Exception) request.getSession()
				.getAttribute(key);
		String error = "";
		if (exception instanceof BadCredentialsException) {
			error = "Invalid username and password!";
		} else if (exception instanceof LockedException) {
			error = exception.getMessage();
		} else {
			error = "Invalid username and password!";
		}
		return error;
	}

}
